/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-return */
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ErrorCode } from '../constants/error-code.enum';
import GlobalApi from 'src/typings/global';

/**
 * 响应转换拦截器
 * 用于统一处理响应格式
 */
@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, GlobalApi.ResponseType<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<GlobalApi.ResponseType<T>> {
    return next.handle().pipe(
      map((data) => {
        // 如果返回的数据已经是标准响应格式，则直接返回
        if (
          data &&
          data.code !== undefined &&
          data.result !== undefined &&
          data.msg !== undefined
        ) {
          return data;
        }

        // 否则，将数据包装成标准响应格式
        return {
          code: ErrorCode.SUCCESS,
          result: data,
          msg: 'success',
        };
      }),
    );
  }
}
